package com.ecoolex.discount.sales.core.service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.discount.sales.core.external.UPlanCouponExternalService;
import com.ecoolex.discount.sales.core.external.pojo.coupon.response.UPlanCouponDeleteResponse;
import com.ecoolex.discount.sales.core.external.pojo.coupon.response.UPlanCouponFetchResponse;
import com.ecoolex.discount.sales.core.manager.UPlanCouponManager;
import com.ecoolex.discount.sales.entity.UPlanCoupon;
import com.ecoolex.discount.sales.entity.UPlanCouponBatch;
import com.ecoolex.discount.sales.enums.UPlanCouponStatus;
import com.ecoolex.framework.common.exception.BizException;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UPlanCouponService {

	@Autowired
	UPlanCouponExternalService uPlanCouponExternalService;

	@Autowired
	UPlanCouponManager uPlanCouponManager;

	final static String SYSTEM_USER = "superadmin";

	final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

	static final int LIMIT = 200;

	public void fetchTimes(UPlanCouponBatch batch, int amount) {
		if (amount > LIMIT) {
			throw new BizException("超过限制无法处理请求");
		}
		for (int i = 1; i <= amount; i++) {
			saveCoupon(batch, i);
		}

	}

	public UPlanCoupon saveCoupon(UPlanCouponBatch batch, String refNumb) {
		try {
			UPlanCouponFetchResponse response = uPlanCouponExternalService.fetch(refNumb, batch.getPromotionCode());
			UPlanCoupon entity = new UPlanCoupon();
			entity.setCouponCode(response.getCouponId());
			if (org.springframework.util.StringUtils.hasText(response.getValidStartDate())) {
				try {
					LocalDateTime validStartDate = LocalDateTime.parse(response.getValidStartDate() + "000000",
							DATE_TIME_FORMATTER);
					entity.setValidStartDate(Date.from(validStartDate.toInstant(ZoneOffset.ofHours(8))));
				}
				catch (Exception ignore) {
					log.error("validStartDate", ignore);
				}
			}

			if (org.springframework.util.StringUtils.hasText(response.getValidEndDate())) {
				try {
					LocalDateTime validEndDate = LocalDateTime.parse(response.getValidEndDate() + "235959",
							DATE_TIME_FORMATTER);
					entity.setValidEndDate(Date.from(validEndDate.toInstant(ZoneOffset.ofHours(8))));
				}
				catch (Exception ignore) {
					log.error("validEndDate", ignore);
				}
			}
			entity.setBatchId(batch.getId());
			entity.setPromotionCode(batch.getPromotionCode());
			entity.setReference(refNumb);
			entity.setStatus(UPlanCouponStatus.AVAILABLE.real());
			entity.setDeleted(UPlanCoupon.NOT_DELETED);
			Date now = Date.from(Instant.now());
			entity.setCreateTime(now);
			entity.setCreateUser(SYSTEM_USER);
			entity.setUpdateTime(now);
			entity.setUpdateUser(SYSTEM_USER);
			uPlanCouponManager.save(entity);
			return entity;
		}
		catch (Exception e) {
			log.error("saveCoupon", e);
			throw new BizException(e.getMessage());
		}
	}

	void saveCoupon(UPlanCouponBatch batch, int current) {
		String data = LocalDateTime.now().format(DATE_TIME_FORMATTER);
		String sequece = StringUtils.leftPad(String.valueOf(current), 4, "0");
		String refNumb = String.format("%s%s", data, sequece);
		saveCoupon(batch, refNumb);
	}

	public void destory(UPlanCoupon coupon) {
		UPlanCouponDeleteResponse response = uPlanCouponExternalService.destory(coupon.getCouponCode());
		if (UPlanCouponExternalService.SUCCESS.equalsIgnoreCase(response.getRespCode())) {
			coupon.setStatus(UPlanCouponStatus.DESTROY.real());
			uPlanCouponManager.updateStatus(coupon);
		}
	}
}
